<?php

declare(strict_types=1);
/**
 * @author liguoxin
 * @email guoxinlee129@gmail.com
 */
namespace App\Controller;

use App\Constant\StatusCode;
use App\Dao\UserDao;
use App\Exception\BadRequestException;
use App\Kernel\Response;
use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\ValidationException;

/**
 * @AutoController
 */
class UserController extends BaseController
{
    /**
     * @Inject
     */
    protected ValidatorFactoryInterface $validationFactory;

    /**
     * @Inject
     */
    protected UserDao $dao;

    /**
     * @Inject
     */
    protected UserService $service;

    public function register(): \Psr\Http\Message\ResponseInterface
    {
        $data = $this->service->register($this->request);
        return $this->successJson(Response::getResult(StatusCode::SUCCESS, [], $data));
    }

    public function find(): \Psr\Http\Message\ResponseInterface
    {
        $validator = $this->validationFactory->make(
            $this->request->all(),
            [
                'id' => 'required|integer|max:100000000',
            ]
        );
        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
        $id = $this->request->input('id');
        $data = $this->dao->find((int) $id);
        return $this->successJson(Response::getResult(StatusCode::SUCCESS, [], $data));
    }

    public function findFromCache(): \Psr\Http\Message\ResponseInterface
    {
        $validator = $this->validationFactory->make(
            $this->request->all(),
            [
                'id' => 'required|integer|max:100000000',
            ]
        );
        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
        $id = $this->request->input('id');
        $data = $this->dao->findFromCache((int) $id);
        return $this->successJson(Response::getResult(StatusCode::SUCCESS, [], $data));
    }

    public function findMany(): \Psr\Http\Message\ResponseInterface
    {
        $ids = $this->request->input('ids', []);
        if (! $ids) {
            throw new BadRequestException();
        }
        $data = $this->dao->findMany($ids);
        return $this->successJson(Response::getResult(StatusCode::SUCCESS, [], $data));
    }

    public function findManyFromCache(): \Psr\Http\Message\ResponseInterface
    {
        $ids = [1000, 1001, 1002, 1003];
        $data = $this->dao->findManyFromCache($ids);
        return $this->successJson(Response::getResult(StatusCode::SUCCESS, [], $data));
    }
}
